<template>
	<view>
		<form @submit="formSubmit">
			<view class="uni-form-item uni-column" v-if="companys.length">
				<view class="title">所属单位
					<text v-if="error_messages.cid" class="text-red">{{ error_messages.cid }}</text>
				</view>
				<picker mode="multiSelector" @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray" range-key="name">
					<view class="uni-input">{{multiArray[0][multiIndex[0]].name}} - {{multiArray[1][multiIndex[1]].name}}</view>
				</picker>
			</view>
			<view class="uni-btn-v" style="padding:9px 3%;">
				<button type="primary" formType="submit">修改单位</button>
			</view>
		</form>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import * as types from 'store/mutations_types'
	import * as API from 'server/getData'

	export default {
		components: {
		},
		data() {
			return {
				multiIndex: [0, 0],
				multiArray: [[], []],
				companys: [],
				error_messages: [],
				form: {
					cid: '',
				}
			}
		},
		onLoad() {
			this.get_companys()
		},
		computed: {
			...mapState(['user'])
		},
		methods: {
			async get_companys() {
				let res = await API.articles.fetchCompanys()
				if (res.success === true) {
					this.companys = res.data.items
					this.multiArray[0] = [{'name': '请选择'}].concat(this.companys.filter((v) => v.pid === 0))
					// this.multiArray[0] = this.companys.filter((v) => v.pid === 0)
					this.multiArray[1] = [{'name': '请选择'}].concat(this.companys.filter((v) => v.pid !== 0))
				}
			},
			bindMultiPickerColumnChange: function(e) {
				this.multiIndex[e.detail.column] = e.detail.value
				switch (e.detail.column) {
					case 0: //拖动第1列
						this.multiArray[1] = this.companys.filter((v) => {
							return v.pid === this.multiArray[0][this.multiIndex[0]].id
						})
						this.form.cid = this.multiArray[1][this.multiIndex[1]].id
						break
					case 1: //拖动第2列
						this.form.cid = this.multiArray[1][this.multiIndex[1]].id
						break
				}
				this.$forceUpdate()
			},

			async formSubmit() {
				let res = await API.user.setting_user_company(this.form)
				if (!res.success) {
					this.error_messages = res.message[0]
					return false
				}
				if (res.success) {
					uni.showToast({title: '修改成功。', duration: 2000})
				}
			}
		}
	}
</script>

<style>
	view {
		font-size: 28upx;
		line-height: inherit
	}
	.text-red {
		color: red;
		margin-left: 10px;
	}
</style>
